﻿// <copyright file="ConnexityChecker.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains a daemon to check connexity issues from time to time by inserting kings in the ConnexityCorrectKings queue.</summary>

namespace Sqwarea.Batch
{
    using System;
    using System.Linq;
    using Lokad.Cloud.ServiceFabric;
    using Lokad.Cloud.Services;
    using Lokad.Cloud.Storage;
    using Sqwarea.GameLogic.Connexity;
    using Sqwarea.Persistence;

    /// <summary>
    /// A daemon that checks connexity issues from time to time by inserting kings in the ConnexityCorrectKings queue
    /// </summary>
    [ScheduledServiceSettings(
        AutoStart = true,
        ProcessingTimeoutSeconds = GlobalParameters.ConnexityCheckerTimeOutSeconds,
        TriggerInterval = GlobalParameters.ConnexityCheckerIntervalSecond)]
    public class ConnexityChecker : ScheduledService 
    {
        /// <summary>
        /// A random number generator
        /// </summary>
        private readonly Random _random = new Random();

        /// <summary>
        /// Gets or sets game provider (given by AutoFac Property Injection)
        /// </summary>
        public IGameProvider GameProvider { get; set; }

        /// <summary>
        /// Gets or sets queue provider (given by AutoFac Property Injection)
        /// </summary>
        public IQueueProvider QueueProvider { get; set; }

        /// <summary>
        /// Scheduled run of a connexity issue checking
        /// </summary>
        protected override void StartOnSchedule()
        {
            if (this.QueueProvider.GetConnexityKingQueueLength() <= GlobalParameters.ConnexityKingQueueThreshold)
            {
                var bigkings = from k in this.GameProvider.GetAllKings()
                               where k.SquaresNumber >= GlobalParameters.ConnexityKingSquareThreshold
                               select k;
                var n = bigkings.Count();
                var prob = (double) GlobalParameters.ConnexityKingQueueThreshold / n;
                foreach (King bigking in bigkings)
                {
                    if (this._random.NextDouble() < prob)
                    {
                        this.QueueProvider.PutConnexityKingToCorrect(bigking.Id);
                    }
                }
            }
        }
    }
}
